<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm" :disabled="!isHide">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('日程人员')" prop="scheduleStaffId">
            <UserSelect
              v-model="form.scheduleStaffId"
              :placeholder="$t('日程人员')"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('部门')" prop="department">
            <DeptSelect v-model="form.department" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('开始时间')" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('开始时间')"
              disabled
              @change="getWeekByTimeRange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('结束时间')" prop="finishTime">
            <el-date-picker
              v-model="form.finishTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('结束时间')"
              disabled
              @change="getWeekByTimeRange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!--本周日程列表-->
      <div class="area-header" style="margin-top: 15px;">
        <span class="area-header-title">{{ $t('本周日程') }}</span>
      </div>
      <el-table
        v-loading="loading"
        :data="form.oaWeekScheduleList"
        :span-method="arraySpanMethod"
        border
        class="nowrapTable formTable"
      >
        <el-table-column :label="$t('星期')" align="center" prop="weekDay" min-width="40">
          <template slot-scope="scope">
            {{ scope.row.weekDay = getDateWeek(parseTime(scope.row.startTime)) + ' ' + parseTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('开始日期')" align="center" prop="startTime" min-width="50">
          <template slot-scope="scope">
            <el-form-item :prop="'oaWeekScheduleList.' + scope.$index + '.startTime'" :rules="oaWeekScheduleListRules.startTime">
              <el-time-picker
                v-model="scope.row.startTime"
                :picker-options="{ selectableRange: '00:00:00 - 23:59:00' }"
                :placeholder="$t('开始日期')"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('结束日期')" align="center" prop="finishTime" min-width="80">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('结束日期') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaWeekScheduleList.' + scope.$index + '.finishTime'" :rules="oaWeekScheduleListRules.finishTime">
              <el-date-picker
                v-model="scope.row.finishTime"
                type="datetime"
                :placeholder="$t('结束日期')"
                value-format="yyyy-MM-dd HH:mm:ss"
                default-time="18:00:00"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否出差')" align="center" prop="travel" min-width="45">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('是否出差') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaWeekScheduleList.' + scope.$index + '.travel'" :rules="oaWeekScheduleListRules.travel">
              <el-radio-group v-model="scope.row.travel">
                <el-radio
                  v-for="dict in travelOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ $t(dict.dictLabel) }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('提醒')" align="center" prop="remind" min-width="55">
          <template slot="header" slot-scope="{}">
            <!--            <i style="color: #ff4949;margin-right: 4px;">*</i>-->
            <span>{{ $t('提醒') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaWeekScheduleList.' + scope.$index + '.travel'">
              <!--              <dictSelect-->
              <!--                v-model="scope.row.remind"-->
              <!--                :clearable="true"-->
              <!--                dictionary="remind_type"-->
              <!--              />-->
              <el-select v-model="scope.row.remind" filterable clearable>
                <el-option
                  v-for="dict in reminds"
                  :key="dict.dictValue"
                  :label="$t(dict.dictLabel)"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('随行人员')" align="center" prop="mechanismName" min-width="70">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('随行人员') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaWeekScheduleList.' + scope.$index + '.entourage'" :rules="oaWeekScheduleListRules.entourage">
              <UserSelect
                v-model="scope.row.entourage"
                :multiple="true"
                :placeholder="$t('随行人员')"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('日程描述')" align="center" prop="schedule" min-width="70">
          <template slot-scope="scope">
            <el-input v-model="scope.row.schedule" :placeholder="$t('日程描述')" show-word-limit maxlenth="200" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('操作')" align="center" width="100">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-plus" @click="addWeekHandle(scope.$index, scope.row)" />
            <el-button v-hasPermi="['oa:weekSchedule:remove']" type="text" icon="el-icon-delete" @click="delHandleTerms(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div v-show="isHide" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="oa:mySchedule" />
    </div>
  </div>
</template>

<script>
import {
  saveOaMySchedule,
  getOaMyScheduleByParams,
  getOaWeekByTime
} from '@/api/oa/mySchedule/oaMySchedule'
import { delOaWeekSchedule } from '@/api/oa/weekSchedule/oaWeekSchedule'
import { getUser } from '@/api/system/user'
export default {
  components: {
  },
  data() {
    return {
      // 表单参数
      form: {
        oaWeekScheduleList: []
      },
      travelOptions: [],
      reminds: [],
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {
        scheduleStaffId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        startTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        finishTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      oaWeekScheduleListRules: {
        startTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        finishTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        travel: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      queryParams: {
        scheduleStaffId: this.$store.state.user.userId,
        beginTime: undefined,
        endTime: undefined
      },
      queryByTime: {
        scheduleStaffId: undefined,
        startTime: undefined,
        finishTime: undefined
      },
      isHide: true
    }
  },
  watch: {
    'form.scheduleStaffId': {
      handler(val) {
        if (val !== undefined && val !== null && val !== '') {
          this.userInfo(val)
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getDicts('sys_yes_no').then((response) => {
      this.travelOptions = response.data
    })
    this.getDicts('remind_type').then((response) => {
      this.reminds = response.data
    })
  },
  mounted() {
    this.$bus.$emit('async_done')
  },
  methods: {
    init(data) {
      this.loading = true
      this.reset()
      // data不为空，则是消息通知打开的窗口
      if (data != null) {
        this.queryParams.beginTime = data.beginTime
        this.queryParams.endTime = data.endTime
        this.queryParams.scheduleStaffId = data.scheduleStaffId
      }
      getOaMyScheduleByParams(this.queryParams).then((response) => {
        if (response.data !== null) {
          this.form = response.data
          this.weekCheckingIn()
        } else {
          this.weekCheckingIn()
        }
        this.$set(this.form, 'scheduleStaffId', this.$store.state.user.userId)
        this.loading = false
      })
    },
    // 根据选择的用户不同显示部门
    userInfo(userId) {
      getUser(userId).then((response) => {
        this.form.department = response.data.deptId
      })
    },
    // 根据时间范围进行查询
    getWeekByTimeRange() {
      this.loading = true
      this.queryByTime.scheduleStaffId = this.form.scheduleStaffId
      this.queryByTime.startTime = this.parseTime(this.form.startTime, '{y}-{m}-{d}')
      this.queryByTime.finishTime = this.parseTime(this.form.finishTime, '{y}-{m}-{d}')
      getOaWeekByTime(this.queryByTime).then((response) => {
        if (response.data !== null) {
          this.form = response.data
        }
      })
      this.loading = false
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        scheduleStaffId: this.$store.state.user.userId,
        department: undefined,
        startTime: undefined,
        finishTime: undefined,
        remark: undefined,
        createBy: undefined,
        updateBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        delFlag: undefined,
        oaWeekScheduleList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.myformOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.myformOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    weekCheckingIn() {
      this.weekChecking_inloading = true
      var now = new Date()
      var nowTime = now.getTime()
      var day = now.getDay() || 7 // 不加 || 7.周末会变成下周一
      var oneDayTime = 24 * 60 * 60 * 1000
      var MondayTime = nowTime - (day - 1) * oneDayTime // 显示周一
      var SundayTime = nowTime + (7 - day) * oneDayTime // 显示周日
      this.$set(this.form, 'startTime', this.formatDate(new Date(MondayTime)))
      this.$set(this.form, 'finishTime', this.formatDate(new Date(SundayTime)))
    },
    formatDate(date) {
      var myyear = date.getFullYear()
      var mymonth = date.getMonth() + 1
      var myweekday = date.getDate()
      if (mymonth < 10) {
        mymonth = '0' + mymonth
      }
      if (myweekday < 10) {
        myweekday = '0' + myweekday
      }
      return myyear + '-' + mymonth + '-' + myweekday
    },
    // 添加行信息
    addWeekHandle(index, item) {
      const row = {
        weekDay: '',
        startTime: item.startTime,
        finishTime: '',
        travel: 'N',
        entourage: [],
        schedule: '',
        remind: ''
      }
      if (!(this.form.oaWeekScheduleList instanceof Array)) {
        this.$set(this.form, 'oaWeekScheduleList', [])
      }
      this.$nextTick(() => {
        this.form.oaWeekScheduleList.splice(index + 1, 0, row)
      })
    },
    // 删除投资机构列表中选中的数据
    delHandleTerms(index, row) {
      // eslint-disable-next-line no-undef
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return delOaWeekSchedule(id)
          })
          .then(() => {
            this.form.oaWeekScheduleList.splice(index, 1)
            return this.msgSuccess(this.$t('删除成功'))
          })
          .catch(function() {})
      } else {
        this.form.oaWeekScheduleList.splice(index, 1)
      }
    },
    // 根据日期dateString获取星期几
    getDateWeek(dateString) {
      if (dateString !== null) {
        var dateArray = dateString.split('-')
        var date = new Date(
          dateArray[0],
          parseInt(dateArray[1] - 1),
          dateArray[2]
        )
        return '周' + '日一二三四五六'.charAt(date.getDay())
      }
    },
    // eslint-disable-next-line no-unused-vars
    arraySpanMethod({ rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const spanArr = this.rowspan()
        for (let i = 0; i < spanArr.length; i++) {
          const _row = spanArr[rowIndex]
          return {
            rowspan: _row,
            colspan: 1
          }
        }
      }
    },
    rowspan() {
      // 二维数组，用于存放单元格合并规则
      const spanArr = []
      // 用于存储相同项的开始index
      let position = 0
      this.form.oaWeekScheduleList.forEach((item, index) => {
        if (index === 0) {
          spanArr.push(1)
          position = 0
        } else {
          if (
            this.form.oaWeekScheduleList[index].weekDay ===
            this.form.oaWeekScheduleList[index - 1].weekDay
          ) {
            spanArr[position] += 1 // 有相同项
            spanArr.push(0) // 名称相同后往数组里面加一项0
          } else {
            spanArr.push(1) // 同列的前后两行单元格不相同
            position = index
          }
        }
      })
      return spanArr
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          saveOaMySchedule(this.form).then((response) => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    }
  }
}
</script>
